from bypy import ByPy
import pandas as pd
from connect import Basic_var
import os
import tarfile
from basic_params import path_today

my_bp = ByPy()


def func_sort(data, df_dic):
    '''
    从que中获取到的数据和header zip成dict
    和df_dic已有数据拼接
    '''
    s = pd.DataFrame(dict(zip(header, data)), index=[0])
    df_dic[data[0]] = pd.concat(
        [df_dic[data[0]], s], ignore_index=True)


def func_store(df_dic):
    '''
    按照储存路径和当前日期trading_day创建path
    按照exg_instrID_list的元素中instr从df_dic选择dataframe并保存为datetime.exg.instr名称格式
    '''
    path = path_today + Basic_var.Trading_day + r'/'
    if not os.path.exists(path_today + Basic_var.Trading_day):
        os.mkdir(path_today + Basic_var.Trading_day)
    for i in Basic_var.excg_instrID_list:
        df_dic[i.split('.')[-1]].to_parquet(path +
                                            Basic_var.Trading_day + '.' + i)
    print('store ended')


def func_pack():
    '''
    选择当前日期path,遍历内容
    修改当前工作路径为当前日期path
    将文件压缩为名称格式datetime.tgz放入当前日期path
    '''
    print('pack start')
    path = path_today + Basic_var.Trading_day + r'/'
    files = os.listdir(path)
    os.chdir(path)
    with tarfile.open(path + Basic_var.Trading_day + '.tgz', "w:gz") as tar:
        for file in files:
            tar.add(file)
    print('pack ended')


def func_upload():
    '''
    当前日期path选择datetime.tgz上传
    '''
    print('upload start')
    path = path_today + Basic_var.Trading_day + r'/'
    my_bp.upload(localpath=path + Basic_var.Trading_day +
                 '.tgz', ondup='newcopy')
    print('upload ended')


def pack_and_upload():
    func_pack()
    func_upload()
    print('pp end')


header = ['InstrumentID',
          'AskPrice1',
          'AskVolume1',
          'BidPrice1',
          'BidVolume1',
          'AskPrice2',
          'AskVolume2',
          'BidPrice2',
          'BidVolume2',
          'AskPrice3',
          'AskVolume3',
          'BidPrice3',
          'BidVolume3',
          'AskPrice4',
          'AskVolume4',
          'BidPrice4',
          'BidVolume4',
          'AskPrice5',
          'AskVolume5',
          'BidPrice5',
          'BidVolume5',
          'LastPrice',
          'OpenInterest',
          'Volume',
          'Turnover',
          'HighestPrice',
          'LowestPrice',
          'UpdateTime',
          'TradingDay']
